<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意！只允许对第三级分类参数设置相关参数"
        type="warning" :closable="false" show-icon>
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!--选择商品的级联选择框-->
          <el-cascader
            v-model="selectedKeys"
            :options="catelist"
            :props="cascaderProps"
            @change="handleChange" clearable>
          </el-cascader>
        </el-col>
      </el-row>
      <template>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数
            </el-button>
            <el-table :data="manyTableData" stripe border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i"
                          closable @close="removeTag(i,scope.row)">{{item}}
                  </el-tag>
                  <!--添加文本框-->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!--添加按钮-->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">添加标签
                  </el-button>
                </template>
              </el-table-column>
              <!-- 索引列-->
              <el-table-column type="index"/>
              <el-table-column label="参数名称" prop="attr_name"/>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini"
                             @click="showEditDialog(scope.row.attr_id)">编辑
                  </el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini"
                             @click="removeParams(scope.row.attr_id)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性
            </el-button>
            <el-table :data="onlyTableData" stripe border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i"
                          closable @close="removeTag(i,scope.row)">{{item}}
                  </el-tag>
                  <!--添加文本框-->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <!--添加按钮-->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">添加标签
                  </el-button>
                </template>
              </el-table-column>
              <!-- 索引列-->
              <el-table-column type="index"/>
              <el-table-column label="参数名称" prop="attr_name"/>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini"
                             @click="showEditDialog(scope.row.attr_id)">编辑
                  </el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini"
                             @click="removeParams(scope.row.attr_id)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>
    <!--添加参数对话框-->
    <el-dialog
      :title="'添加'+ titleText"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="paramsDialogClosed"
    >
      <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改参数对话框-->
    <el-dialog
      :title="'修改'+ titleText"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <el-form :model="editParamsForm" :rules="editParamsRules" ref="editParamsRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateParamsInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Params",
    data() {
      return {
        catelist: [],
        selectedKeys: [],
        parentCateList: [],
        cascaderProps: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
        },
        activeName: 'many',
        manyTableData: [],
        onlyTableData: [],
        editParamsForm: {
          attr_name: ''
        },
        addParamsForm: {
          attr_name: ''
        },
        editDialogVisible: false,
        addDialogVisible: false,
        editParamsRules: {
          attr_name: [
            {required: true, message: '请输入参数名称', trigger: 'blur'},
            {
              min: 1,
              max: 20,
              message: '长度在 1 到 20 个字符',
              trigger: 'blur'
            }
          ]
        },
        addParamsRules: {
          attr_name: [
            {required: true, message: '请输入参数名称', trigger: 'blur'},
            {
              min: 1,
              max: 20,
              message: '长度在 1 到 20 个字符',
              trigger: 'blur'
            }
          ]
        },
      }
    },
    created() {
      this.getCateList()
    },
    methods: {
      getCateList() {
        this.$store.dispatch('getCateParamsList_').then(() => {
          this.catelist = this.$store.state.params_cate_list
        })
      },
      handleChange() {
        this.getParamsData()
      },
      handleTabClick() {
        this.getParamsData()
      },
      getParamsData() {
        if (this.selectedKeys.length !== 3) {
          this.selectedKeys = []
          this.manyTableData = []
          this.onlyTableData = []
          return
        }
        //根据所选分类id和所选面板获取对应参数
        let params = {
          id: this.cateId,
          sel: {sel: this.activeName}
        }
        this.$store.dispatch('getParamsList_', params).then(() => {
          if (this.$store.state.params_state !== 200) {
            return this.$message.error("获取参数列表失败")
          }
          const res = this.$store.state.params
          res.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            //控制文本框的显示与隐藏
            item.inputVisible = false
            //文本框中输入的值
            this.inputValue = ''
          })
          if (this.activeName === 'many') {
            this.manyTableData = res
          } else {
            this.onlyTableData = res
          }
        })
      },
      paramsDialogClosed() {
        this.$refs.addParamsRef.resetFields()
      },
      editDialogClosed() {
        this.$refs.editParamsRef.resetFields()
      },
      showEditDialog(attr_id) {
        let params = {
          id: this.cateId,
          attr_id: attr_id,
          attr_sel: {attr_sel: this.activeName}
        }
        this.$store.dispatch('getParamsById_', params).then(() => {
          if (this.$store.state.params_state !== 200) {
            return this.$message.error("获取参数失败")
          }
          this.editParamsForm = this.$store.state.params
          this.editDialogVisible = true
        })
      },
      updateParamsInfo() {
        this.$refs.editParamsRef.validate(valid => {
          if ((!valid)) return
          let params = {
            id: this.cateId,
            attr_id: this.editParamsForm.attr_id,
            attr_sel: {
              attr_name: this.editParamsForm.attr_name,
              attr_sel: this.activeName,
              attr_vals: this.editParamsForm.attr_vals
            }
          }
          this.$store.dispatch('updateParamsById_', params).then(() => {
            if (this.$store.state.params_state !== 200) {
              return this.$message.error("修改参数失败")
            }
            this.$message.success("修改参数成功")
            this.getParamsData()
            this.editDialogVisible = false
          })
        })
      },
      addParams() {
        this.$refs.addParamsRef.validate(valid => {
          if ((!valid)) return
          let param = {
            id: this.cateId,
            params: {
              attr_name: this.addParamsForm.attr_name,
              attr_sel: this.activeName
            }
          }
          this.$store.dispatch('addParams_', param).then(() => {
            if (this.$store.state.params_state !== 201) {
              return this.$message.error("添加失败")
            }
            this.getParamsData()
            this.addDialogVisible = false
            return this.$message.success("添加成功")
          })
        })
      },
      removeParams(attr_id) {
        let p = {
          id: this.cateId,
          attr_id: attr_id,
        }
        this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('removeParamsById_', p).then(() => {
            if (this.$store.state.params_state !== 200) {
              return this.$message.error("删除失败")
            }
            this.getParamsData()
            this.$message({type: 'success', message: '删除成功!'});
          })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除'});
        })
      },
      handleInputConfirm(row) {
        console.log("怎么回事", row);
        if (row.inputValue === undefined) {
          row.inputVisible = false
          return
        }
        if (row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        //发起请求保存
        this.saveAttrVals(row)
      },
      //保存参数
      saveAttrVals(row) {
        let param = {
          id: this.cateId,
          attr_id: row.attr_id,
          p: {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(' ')
          }
        }
        this.$store.dispatch('editAddParams_', param).then(() => {
          if (this.$store.state.params_state !== 200) {
            return this.$message.error("修改数据失败")
          }
          this.$message.success("修改数据成功")
        })
      },
      showInput(row) {
        row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      //删除对应参数和选项
      removeTag(i, row) {
        row.attr_vals.splice(i, 1)
        this.saveAttrVals(row)
      }
    },
    computed: {
      //如果按钮被禁用，返回true
      isBtnDisabled() {
        if (this.selectedKeys.length !== 3) {
          return true
        }
        return false
      },
      cateId() {
        if (this.selectedKeys.length === 3) {
          return this.selectedKeys[2]
        }
        return null
      },
      titleText() {
        if (this.activeName === 'many') {
          return '动态参数'
        }
        return '静态属性'
      }
    }
  }
</script>

<style lang="less" scoped>
  .cat_opt {
    margin: 15px 0;
    text-align: left;
  }

  .el-tag {
    margin: 10px;
  }

  .input-new-tag {
    width: 120px;
  }

</style>
